﻿// Copyright (c) 2008 screamingtarget@gmail.com

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.


using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Text;
using System.Windows.Forms;

using NfoViewer.Properties;


namespace NfoViewer
{
   public partial class MainForm : Form
   {
      public MainForm()
      {
         InitializeComponent();
      }

      protected override void OnClosing( CancelEventArgs e )
      {
         base.OnClosing( e );

         Settings.Default.Location = Location;
         Settings.Default.Size = Size;

         Settings.Default.Save();
      }

      protected override void OnLoad( EventArgs e )
      {
         // just for now
         //
         _toolStripOptions.Enabled = false;
         _toolStripCharWrap.Enabled = false;

         base.Location = Settings.Default.Location;
         base.Size = Settings.Default.Size;

         _textBox.BackColor = Settings.Default.BackColor;
         _textBox.Font = Settings.Default.Font;

         _textBox.AutoWordSelection = false;
         _textBox.DetectUrls = true;

         _toolStripOpen.Text = Resources.Open;
         _toolStripOpen.ToolTipText = Resources.OpenToolTip;

         _toolStripOptions.Text = Resources.Options;
         _toolStripOptions.ToolTipText = Resources.OptionsToolTip;

         _toolStripCopy.Text = Resources.Copy;
         _toolStripCopy.ToolTipText = Resources.CopyToolTip;

         _toolStripNoWrap.Text = Resources.NoWrapText;
         _toolStripNoWrap.ToolTipText = Resources.NoWrapToolTip;

         _toolStripCharWrap.Text = Resources.CharWrapText;
         _toolStripCharWrap.ToolTipText = Resources.CharWrapToolTip;

         _toolStripWordWrap.Text = Resources.WordWrapText;
         _toolStripWordWrap.ToolTipText = Resources.WordWrapToolTip;

         _wrapType = (WrapType)Enum.Parse( typeof( WrapType ),
            Settings.Default.WrapType );

         switch ( _wrapType )
         {
            case WrapType.NoWrap:
               _toolStripNoWrap.Checked = true;
               break;
            case WrapType.CharacterWrap:
               _toolStripCharWrap.Checked = true;
               break;
            case WrapType.WordWrap:
               _toolStripWordWrap.Checked = true;
               break;
         }

         SetTextBoxWrapping();

         ClearStatusInfo();

         _statusStripTextBoxSize.Text = TextBoxSize();

         SetMRUList();

         base.OnLoad( e );
      }

      protected override void OnSizeChanged( EventArgs e )
      {
         base.OnSizeChanged( e );
         _statusStripTextBoxSize.Text = TextBoxSize();
      }

      [SuppressMessage( "Microsoft.Globalization",
         "CA1300:SpecifyMessageBoxOptions" )]
      private void OpenFile( string fileName )
      {
         FileInfo fi = new FileInfo( fileName );

         if ( fi.Length > FileSizeMax )
         {
            string message = String.Format( CultureInfo.InvariantCulture,
               Resources.FileTooBig, FileSizeMax / 1024 );
            MessageBox.Show( this, message, Resources.ApplicationName,
               MessageBoxButtons.OK, MessageBoxIcon.Exclamation );
            return;
         }
         
         SuspendLayout();

         _textBox.Clear();

         Text = Resources.ApplicationName;

         File file = new File( fileName,
            Resources.ConversionString );

         if ( file.Load() )
         {
            _textBox.Lines = file.Lines;
            Text += Resources.Separator + file.FileName;
            SetStatusInfo( file );

            StringCollection mru = Settings.Default.MRU;

            if ( mru == null )
            {
               mru = new StringCollection();
            }

            if ( mru.Contains( file.FullPath ) )
            {
               mru.Remove( file.FullPath );
            }

            mru.Insert( 0, file.FullPath );

            int index = mru.Count - 1;

            while ( index >= MRUMax )
            {
               mru.RemoveAt( index );
               --index;
            }

            Settings.Default.MRU = mru;
            Settings.Default.Save();

            SetMRUList();
         }

         _statusStripTextBoxSize.Text = TextBoxSize();

         ResumeLayout();
      }

      private string TextBoxSize()
      {
         Size size = _textBox.TextSize;
         return String.Format( CultureInfo.InvariantCulture,
            Resources.TextBoxSize, size.Width, size.Height );
      }

      private void _toolStripOpen_ButtonClick( object sender, EventArgs e )
      {
         _openFileDialog.Filter = Resources.FileFilter;
         _openFileDialog.FilterIndex = 0;

         if ( _openFileDialog.ShowDialog() == DialogResult.OK )
         {
            OpenFile( _openFileDialog.FileName );
         }
      }

      private void ClearStatusInfo()
      {
         _statusStripPath.Image = null;
         _statusStripPath.Text = String.Empty;

         _statusStripDate.Visible = false;
         _statusStripFileSize.Visible = false;
      }

      private void SetStatusInfo( File file )
      {
         _statusStripDate.Text = file.LastModified.ToShortDateString() + " " +
            file.LastModified.ToShortTimeString();

         _statusStripFileSize.Text = file.Size.ToString( "N0",
            CultureInfo.InvariantCulture );

         _statusStripDate.Visible = true;
         _statusStripFileSize.Visible = true;

         _statusStripPath.Image = file.Image;
         _statusStripPath.Text = file.FullPath;
      }

      protected override void OnDragEnter( DragEventArgs drgevent )
      {
         if ( drgevent.Data.GetDataPresent( DataFormats.FileDrop ) )
         {
            drgevent.Effect = DragDropEffects.Copy;
         }

         base.OnDragEnter( drgevent );
      }

      protected override void OnDragDrop( DragEventArgs drgevent )
      {
         string[] files =
            (string[])drgevent.Data.GetData( DataFormats.FileDrop );

         if ( files != null && files.Length > 0 )
         {
            OpenFile( files[ 0 ] );
         }

         base.OnDragDrop( drgevent );
      }

      private void SetMRUList()
      {
         _toolStripOpen.DropDownItems.Clear();

         StringCollection mru = Settings.Default.MRU;

         if ( mru == null )
         {
            return;
         }

         for ( int index = 0; index < mru.Count; ++index )
         {
            string strIndex = String.Format( CultureInfo.InvariantCulture,
               "&{0} ", index + 1 );
            _toolStripOpen.DropDownItems.Add( strIndex + mru[ index ] );
         }
      }

      private void _toolStripOpen_DropDownItemClicked( object sender,
         ToolStripItemClickedEventArgs e )
      {
         OpenFile( e.ClickedItem.Text.TrimStart( _trimCharacters ) );
      }

      private const int FileSizeMax = 1024 * 1024;

      private const int MRUMax = 9;
      private char[] _trimCharacters = { '&', '0', '1', '2', '3', '4', '5',
         '6', '7', '8', '9', ' ' };

      private WrapType _wrapType;

      private void _toolStripNoWrap_Click( object sender, EventArgs e )
      {
         if ( _toolStripNoWrap.Checked )
         {
            return;
         }

         _toolStripCharWrap.Checked = false;
         _toolStripWordWrap.Checked = false;
         _toolStripNoWrap.Checked = true;

         _wrapType = WrapType.NoWrap;

         SetTextBoxWrapping();
      }

      private void _toolStripCharWrap_Click( object sender, EventArgs e )
      {
         if ( _toolStripCharWrap.Checked )
         {
            return;
         }

         _toolStripWordWrap.Checked = false;
         _toolStripNoWrap.Checked = false;
         _toolStripCharWrap.Checked = true;

         _wrapType = WrapType.CharacterWrap;

         SetTextBoxWrapping();
      }

      private void _toolStripWordWrap_Click( object sender, EventArgs e )
      {
         if ( _toolStripWordWrap.Checked )
         {
            return;
         }

         _toolStripNoWrap.Checked = false;
         _toolStripCharWrap.Checked = false;
         _toolStripWordWrap.Checked = true;

         _wrapType = WrapType.WordWrap;

         SetTextBoxWrapping();
      }

      private void SetTextBoxWrapping()
      {
         _textBox.SuspendLayout();

         _textBox.WrapType = _wrapType;

         _textBox.ResumeLayout();

         Settings.Default.WrapType =
            Enum.GetName( typeof( WrapType ), _wrapType );
         Settings.Default.Save();
      }
   }
}
